Default Parameter Values

Scala provides a feature to assign default values for method parameters. It helps in the scenario when you don't pass value during function calling. It uses default values of parameters.

Method with default parameters
object MainObject {
  def functionExample(a:Int = 0, b:Int = 0):Int = {
        a+b
    }
    def main(args: Array[String]) = {
        var result1 = functionExample(15,2)
        var result2 = functionExample(15)
        var result3 = functionExample() 
        var result4 = functionExample(0,-2) 
       println(result1+"\n"+result2+"\n"+result3+"\n"+result4 )
    }
}


17
15
0
-2

Method with default parameters
object calculateResult {
      def funSub(x:Int=9, y:Int=6) : Int =
   {
       var diff:Int = 0
       diff = x - y
       // return value
       return diff
   }
   def main(args: Array[String]) {
      // Function call
    print( "The final value is: " + funSub() );
   }
}



object test {
  object Math{
  def +(a:Int=20,b:Int=10):Int = {
    a + b
  }
  }
  def **(x:Int=20) = x*x 
  def mul(a:Int,b:Int) = a*b
  def div(a:Int,b:Int) = a/b   
    def main(args: Array[String]) = {
        var result1 = Math.+()
        var result2 = **(30)
        var result3 = mul(15,2)
        var result4 = div(15,2)
        println(result1+"\n"+result2+"\n"+result3+"\n"+result4 )
    }
}

No comments:

Post a Comment